/**
 * @desc: 二类户（新，老（小））开户绑卡一体化流程
 * @author: binlety
 */

import { useState, useEffect, useRef } from "react";
import { Form, Button, Input, Alert, Modal, message } from 'antd';
import CommonModal from "@/components/CommonModal";
import CommonQinnvImgsLoad from './CommonQinnvImgsLoad';
import NewBindCardModal from './NewBindCardModal';
import { submitCardOp } from './service';
import styles from './index.module.less';
import ComfortableTipsModal from "./ComfortableTipsModal";

 const layout = {
  labelCol: {
    span: 5,
  },
  wrapperCol: {
    span: 17,
  }
};

const NewOpenAccountModal = ({ title, handleOk, handleCancel }) => {

  const [form] = Form.useForm();

  const [visible, setVisible] = useState(false);//1.新平安绑卡modal
  const [tipsMsg, setTipsMsg] = useState(null);//温馨提示弹窗

  const [leftKey, setLeftKey] = useState(0);
  const [rightKey, setRightKey] = useState(0);

  const stageData = useRef({
    front: false,
    back: false,
    address: undefined,
    cityCode: undefined,
    countyCode: undefined,
    panCardUploadSn: undefined,//平安影像审核编码
    provinceCode: undefined,
  })

  //平安影像审核
  const onOk = () => {
    form.validateFields().then(async value => {
      setTipsMsg({ type: 2 });
      const { frontUrl, backUrl, name, idCard } = value;
      const { front, back, address } = stageData.current;
      const { data, success } = await submitCardOp({
        frontUrl, 
        backUrl, 
        name, 
        idCard,
        front, 
        back, 
        address
      });
      if (success) {
        stageData.current = { ...stageData.current, ...(data || {})}
        setVisible(1);
      }
      setTipsMsg(null);
    })
  }

  //图片上传回调手动更新表单值
  const handleDone = (type, res, file) => {
    const { success, data, msg } = res;
    if(success){
      const { name, cardNo, nation, address, cardFrontUrl, cardBackUrl, expiryDate, issueDate } = data || {};
      if(type == 'front'){
        stageData.current[type] = file;
        stageData.current.address = address;
        form.setFieldsValue({
          name,
          nation,
          address,
          idCard: cardNo,
          frontUrl: cardFrontUrl
        });
      }else if(type == 'back'){
        stageData.current[type] = file;
        form.setFieldsValue({
          backUrl: cardBackUrl,
          time: `${issueDate} - ${expiryDate}`
        });
      }
    }else{
      setTipsMsg({
        type: 1,
        key: type,
        reason: msg
      })
    }
  };

  //温馨提示modal
  const tipsModalProps = {
    tipsMsg,
    handleOk(){
      tipsMsg.key == 'front' && setLeftKey(leftKey + 1);
      tipsMsg.key == 'back' && setRightKey(rightKey + 1);
      setTipsMsg(null);
    }
  }

  //新绑卡modal
  const bindCardProps = {
    params: stageData,
    handleOk(){
      handleOk();
    },
    handleCancel() {
      setVisible(false);
    }
  }

  return (
    <CommonModal
      title={title}
      visible={true}
      onCancel={handleCancel}
      width='765px'
      okText="提交"
      onOk={onOk}
    >
      <Alert message='鉴于银行监管要求，以及不影响后续系统操作，需要您完善以下信息进行实名验证！' />

      <Form name='open-second-account-form' form={form} {...layout} style={{ marginTop: '8px' }}>
        <Form.Item label={<span className="lable-require">身份证照片</span>}>
          <div style={{ display: 'flex' }}>
            <div>
              <Form.Item name="frontUrl" rules={[{ required: true, message: '图片不能为空' }]} style={{ marginBottom: '0px' }}>
                <CommonQinnvImgsLoad
                  key={leftKey}
                  className="rectangleSmall"
                  actionUrl='/zjf-pays/imgOcr/cardFront'
                  customText='身份证人像面'
                  size={1}
                  handleOk={(val, file) => handleDone('front', val, file)}
                  handleFailed={()=>setLeftKey(leftKey+1)}
                  customNode={<div className={`${styles.uploadWrap} ${styles.identityFront}`}><div className={styles.uploadIconBox}>+</div></div>}
                />
              </Form.Item>
              <p style={{ textAlign: 'center' }}>身份证人像面</p>
            </div>
            <div>
              <Form.Item name="backUrl" rules={[{ required: true, message: '图片不能为空' }]} style={{ marginBottom: '0px' }}>
                <CommonQinnvImgsLoad
                  key={rightKey}
                  className="rectangleSmall"
                  actionUrl='/zjf-pays/imgOcr/cardBack'
                  customText='身份证国徽面'
                  size={1}
                  handleOk={(val, file) => handleDone('back', val, file)}
                  handleFailed={()=>setRightKey(rightKey+1)}
                  customNode={<div className={`${styles.uploadWrap} ${styles.identityBack}`}><div className={styles.uploadIconBox}>+</div></div>}
                />
              </Form.Item>
              <p style={{ textAlign: 'center' }}>身份证国徽面</p>
            </div>
          </div>
        </Form.Item>

        <Form.Item
          label="开户人姓名"
          name="name"
          rules={[{ required: true, message: '请输入开户人姓名'}, { pattern: /^[\u4e00-\u9fa5\·•]{1,20}$/g, message: '请输入文字' }]}
        >
          <Input maxLength={20} />
        </Form.Item>

        <Form.Item
          label="身份证号"
          name="idCard"
          rules={[{ required: true, message: '请输入身份证号' }, { pattern: /^[0-9a-zA-Z]{1,20}$/g, message: '仅支持数字和字母' }]}
        >
          <Input maxLength={20}/>
        </Form.Item>

        <Form.Item
          label="民族"
          name="nation"
          rules={[{ required: true, message: '请输入民族' }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="身份证有效期"
          name="time"
          rules={[{ required: true, message: '请输入身份证有效期' }]}
        >
          <Input />
        </Form.Item>
      </Form>

      {/* 温馨提示 */}
      {tipsMsg && <ComfortableTipsModal { ...tipsModalProps} />}
      {/* <CommonModal
        title='温馨提示'
        visible={comfortableMsg}
        width={416}
        onCancel={()=>setTipsMsg('')}
        footer={<Button type="primary" onClick={()=>setTipsMsg('')}>知道了</Button>}
      >
        <div className="common-color9" style={{ fontSize: '15px', display: 'flex', alignItems: "center", paddingLeft: '8px' }}>{svg}&nbsp;识别失败</div>
        <p style={{ marginTop: '2px', textIndent: '28px' }}>{comfortableMsg}</p>
      </CommonModal> */}

      {/* 新绑卡 */}
      {visible == 1 && <NewBindCardModal {...bindCardProps} />}

    </CommonModal>
  )
}

export default NewOpenAccountModal;